package cn.itsource.order.service.impl;

import cn.itsource.basic.constant.PetHomeConstant;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.CodeGenerateUtils;
import cn.itsource.basic.util.DistanceUtil;
import cn.itsource.order.domain.OrderAddress;
import cn.itsource.order.domain.ProductOrder;
import cn.itsource.order.domain.ProductOrderDetail;
import cn.itsource.order.mapper.OrderAddressMapper;
import cn.itsource.order.mapper.ProductOrderDetailMapper;
import cn.itsource.order.mapper.ProductOrderMapper;
import cn.itsource.order.service.IProductOrderService;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.product.domain.Product;
import cn.itsource.product.mapper.ProductMapper;
import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.UserAddress;
import cn.itsource.user.mapper.UserAddressMapper;
import cn.itsource.user.mapper.UserMapper;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder>implements IProductOrderService {
   @Autowired
   private UserMapper userMapper;
   @Autowired
   private UserAddressMapper userAddressMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductOrderMapper productOrderMapper;
    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Override
    @Transactional
    public void submitOrder(Map<String, Object> map, LoginInfo loginInfo) {
        //获取用户地址id
        Long addressId = Long.valueOf(map.get("addressId").toString());
        //获取支付方式
        Integer payType = (Integer)map.get("payType");
        //获取服务id和购买数量
        List<Map<String,Integer>> list=(List<Map<String,Integer>>)map.get("products");
        //获取登录人信息
        User user=userMapper.lodaUserById(loginInfo.getId());
        //获取登录人地址
        UserAddress userAddress= userAddressMapper.findById(addressId);
        //创建服务订单
        ProductOrder order=createProductOrder(list,user);
        //获取最近的店铺
        Shop nearestShop = DistanceUtil.getNearestShop(DistanceUtil.getPoint(userAddress.getFullAddress()), shopMapper.findAll());
        //设置店铺
        order.setShop(nearestShop);
        //保存服务订单
        productOrderMapper.save(order);
        //创建服务明细订单
        List<ProductOrderDetail> details = createProductDetailOrder(list,order);
        //批量保存服务详情订单
        productOrderDetailMapper.batchSave(details);
        //创建订单地址
        OrderAddress orderAddress = createOrderAddress(userAddress,order.getOrderSn());
        //订单地址mapper的保存
        orderAddressMapper.save(orderAddress);

    }
    //创建订单地址
    private OrderAddress createOrderAddress(UserAddress userAddress, String orderSn) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress, orderAddress);
        orderAddress.setCreateTime(new Date());
        orderAddress.setOrderSn(orderSn);
        return orderAddress;
    }

    //创建服务明细订单
    private List<ProductOrderDetail> createProductDetailOrder(List<Map<String, Integer>> list, ProductOrder order) {
        //创建一个集合，专门来封装服务订单明细
        List<ProductOrderDetail> details = new ArrayList<>();
        for (Map<String, Integer> map : list) {
            //获取服务id
            Long id = Long.valueOf(map.get("id").toString());
            //获取服务数量
            Integer num = Integer.valueOf(map.get("num").toString());
            ProductOrderDetail productOrderDetail = new ProductOrderDetail();
            //设置创建时间
            productOrderDetail.setCreateTime(new Date());
            //设置服务订单
            productOrderDetail.setOrder(order);
            //设置服务对象
            Product product = new Product();
            product.setId(id);
            productOrderDetail.setProduct(product);
            //设置销售数量
            productOrderDetail.setSaleCount(num);
            details.add(productOrderDetail);
        }
        return details;
    }

    //创建服务订单
    private ProductOrder createProductOrder(List<Map<String, Integer>> list, User user) {
        ProductOrder productOrder = new ProductOrder();
        StringBuilder sb = new StringBuilder();
        //计算明细的总金额
        BigDecimal totalAmount = new BigDecimal("0");
        for (int i = 0; i < list.size(); i++) {
            Map<String, Integer> map = list.get(i);
            //服务id
            Long id = Long.valueOf(map.get("id").toString());
            //服务数量
            Integer num = Integer.valueOf(map.get("num").toString());
            //通过服务id查询服务对象
            Product product = productMapper.findById(id);
            //计算小计
            BigDecimal subtotal = new BigDecimal(num).multiply(product.getSaleprice());
            //累加金额
            totalAmount = totalAmount.add(subtotal);
            //添加服务名
            sb.append(product.getName());
            if(i!=list.size()-1) {
                sb.append(",");
            }
        }
        productOrder.setDigest("[摘要]对" + sb + "产生服务订单");
        //待支付
        productOrder.setState(PetHomeConstant.UNPAID);
        //设置总金额
        productOrder.setPrice(totalAmount);
        //哪个用户下的订单
        productOrder.setUser(user);
        //订单编号
        productOrder.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        //最后支付时间
        productOrder.setLastPayTime(DateUtils.addMinutes(new Date(),15));
        return productOrder;
    }
}
